package com.ruoyi.wechat.controller;

import com.ruoyi.wechat.common.ServiceException;
import com.ruoyi.wechat.domain.AppUser;
import com.ruoyi.wechat.domain.form.LoginForm;
import com.ruoyi.wechat.domain.vo.AjaxResult;
import com.ruoyi.wechat.domain.vo.LoginData;
import com.ruoyi.wechat.service.IAppUserService;
import com.ruoyi.wechat.service.IAuthService;
import com.ruoyi.wechat.utils.LoginHelper;
import com.ruoyi.wechat.utils.WechatHelper;
import org.apache.http.HttpStatus;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping
public class TokenController {

    @Autowired
    private IAppUserService appUserService;

    @Autowired
    private WechatHelper wechatHelper;

    @Autowired
    private IAuthService authService;

    /**
     * 登录时获取的 code（微信官方提供的临时凭证）
     *
     * @param
     * @return
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginForm form) {
        //如果账号不为空，则账号登录
        if (!ObjectUtils.isEmpty(form.getAccount())) {
            //如果短信验证码不为空，则为短信验证码登录
            if (!ObjectUtils.isEmpty(form.getSmsCode())) {
                LoginData loginData = authService.smsAuth(form.getAccount(), form.getSmsCode());
                return AjaxResult.success(loginData, "登录成功");
            }
            //密码登录
            else if (!ObjectUtils.isEmpty(form.getPassword())) {
                LoginData loginData = authService.pwdAuth(form.getAccount(), form.getPassword());
                return AjaxResult.success(loginData, "登录成功");
            }
        }
        //微信小程序登录
        if (!ObjectUtils.isEmpty(form.getCode())) {
            LoginData loginData = authService.openidAuth(form.getCode());
            return AjaxResult.success(loginData, "登录成功");
        }

        return AjaxResult.error(HttpStatus.SC_INTERNAL_SERVER_ERROR, "账号异常");

    }

    /**
     * 获取用户信息
     *
     * @return
     */
    @GetMapping("/getInfo")
    public AjaxResult getInfo() {
        Long userId = LoginHelper.getSession().getAppUser().getId();
        AppUser user = appUserService.getById(userId);
        if (ObjectUtils.isEmpty(user)){
            throw new ServiceException(HttpStatus.SC_UNAUTHORIZED,"登录失效，请重新登录");
        }
        LoginData.UserInfo userInfo = new LoginData.UserInfo();
        BeanUtils.copyProperties(user, userInfo);
        return AjaxResult.success(userInfo, "OK");
    }


}
